package com.jason.concurrent.signal;
//第一步就是创建一个资源类

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SharePrint{

    // 定义一个属性

    private int flag = 1;

    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();
    // 定义方法

    public void print1(int loop) {


        //
        lock.lock();

        try {
            //判断
            while(flag!=1){
                c1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+"::"+i+"第几轮"+loop);
            }
            flag = 2;
            c2.signal();
        } catch (Exception e) {
        }
        finally {
            lock.unlock();
        }

    }
    public void print2(int loop) {


        //
        lock.lock();

        try {
            //判断
            while(flag!=2){
                c2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+"::"+i+"第几轮"+loop);
            }
            flag = 3;
            c3.signal();
        } catch (Exception e) {
        }
        finally {
            lock.unlock();
        }

    }
    public void print3(int loop) {


        //
        lock.lock();

        try {
            //判断
            while(flag!=3){
                c3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName()+"::"+i+"第几轮"+loop);
            }
            flag = 1;
            c1.signal();
        } catch (Exception e) {
        }
        finally {
            lock.unlock();
        }

    }

    // 判断

    //干活

    //通知
    //解锁操作
    //
}
public class LoopPrint {
    public static void main(String[] args) {
        //调用方法

        SharePrint sharePrint = new SharePrint();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                sharePrint.print1(i);
            }
        },"aa").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                sharePrint.print2(i);
            }
        },"bb").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                sharePrint.print3(i);
            }
        },"cc").start();
    }
}
